using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using Lavka.Core;
using Lavka.Models;

namespace Lavka.Controllers
{   
    public class ProductsController : Controller
    {
        private LavkaDbEntities context = new LavkaDbEntities();

        bool SortAscending
        {
            get
            {
                if (Session["SortAscending"] == null) Session["SortAscending"] = true;
                return (bool)Session["SortAscending"];
            }
            set { Session["SortAscending"] = value; }            
        }

        SortFilter SortFilter
        {
            get
            {
                if(Session["SortFilter"] == null) Session["SortFilter"] = SortFilter.Name;
                return (SortFilter)Session["SortFilter"];
            }
            set { Session["SortFilter"] = value; }
        }

        public int ListPageIndex 
        { 
            get
            {
                if (Session["ListPageIndex"] == null) Session["ListPageIndex"] = 0;
                return (int) Session["ListPageIndex"];
            }
            set { Session["ListPageIndex"] = value; }
             
        }

        public List<Articles> CurrentArticles
        {
            get {
                if (Session["ProductArticles"] == null)
                Session["ProductArticles"] = new List<Articles>();
                return (List<Articles>)Session["ProductArticles"]; 
            }
            set { Session["ProductArticles"] = value; }
        }

        //
        // GET: /Catalog/
        public ViewResult Index()
        {
            if (ValidateRequest)
            {
                ViewData["Brands"] = context.Brands.ToList();
                return View(context.Caterories.ToList());
            }
            return null;                 
        }
        public ViewResult Sort(SortFilter filter)
        {
            if(SortFilter == filter)
            {
                SortAscending = !SortAscending;
            }
            SortFilter = filter;
            Response.Redirect(Request.UrlReferrer.ToString());
            return null;
        }

        public ViewResult List()
        {
            ListPageIndex = 0;
            if (ValidateRequest)
            {
                ViewBag.SortFilter = SortFilter;
                ViewBag.SortAscending = SortAscending;
                ViewBag.categoryId = 0;
                ViewData["Brands"] = context.Brands.ToList();
                return View(ProductsHelper.GetProducts(0, context, SortFilter, SortAscending));
            }
            return null;            
        }

        public ViewResult Galery()
        {
            ListPageIndex = 0;
            if (ValidateRequest)
            {
                ViewBag.SortFilter = SortFilter;
                ViewBag.SortAscending = SortAscending;
                ViewBag.categoryId = 0;
                ViewData["Brands"] = context.Brands.ToList();
                return View(ProductsHelper.GetProducts(0, context, SortFilter, SortAscending));
            }
            return null;
        }

        [HttpPost]
        public PartialViewResult LoadContentListPart(int categoryId)
        {
            ListPageIndex++;
            return PartialView("ProductsList", ProductsHelper.GetProducts(categoryId, ListPageIndex, 
                context, SortFilter, SortAscending));
        }

        [HttpPost]
        public PartialViewResult LoadContentGaleryPart()
        {
            ListPageIndex++;
            return PartialView("ProductsGalery", ProductsHelper.GetProducts(ListPageIndex, context, SortFilter, SortAscending));
        }

        [HttpGet]
        public ViewResult Category(int categoryId)
        {
            ListPageIndex = 0;
            if (ValidateRequest)
            {
                ViewBag.SortFilter = SortFilter;
                ViewBag.SortAscending = SortAscending;
                ViewBag.categoryId = categoryId;
                return View(ProductsHelper.GetProducts(categoryId, context, SortFilter, SortAscending));
            }
            return null;
        }

        public ViewResult Brand(int brandId)
        {
            if (ValidateRequest)
            {
                //.Where(p => p.CategoryId == categoryId)
                return View(context.Products.Where(p => p.BrandId == brandId).ToList());
            }
            return null;
        }

        [HttpPost]
        public ViewResult Details(Products product)
        {
            CartHelper.AddProductById(product.ProductId, context);
            return Details(product.ProductId);
        }
        //
        // GET: /Catalog/Details/5
        public ViewResult Details(int id)
        {
            Products products = context.Products.Single(x => x.ProductId == id);

            if (ProductsHelper.ViewedProducts.Where(p => p.ProductId == products.ProductId).Count<Products>() == 0)
            ProductsHelper.ViewedProducts.Add(products);

            ViewData["Parameters"] = ParametersValuesHelper.GetParametersValuesForProduct(id);
            return View(products);
        }

        //
        // GET: /Catalog/Create
        public ActionResult Create()
        {
            var firstCategory = CategoriesHelper.GetCategories(false, context).First();
            ViewData["Brands"] = new SelectList(context.Brands.ToList(), "BrandId", "Name");
            ViewData["Categories"] = new SelectList(CategoriesHelper.GetCategories(false, context), "CategoryId", "Name");
            ViewData["Parameters"] = ParametersHelper.GetParametersByCategoryId(firstCategory.CategoryId);
            return View();
        } 

        //
        // POST: /Catalog/Create

        [HttpPost]
        [Authorize(Roles = "Administrators")]
        [ValidateInput(false)]
        public ActionResult Create(Products products, HttpPostedFileBase file)
        {
            products.BrandId = Convert.ToInt32(Request.Form["ddlBrands"]);
            products.CategoryId = Convert.ToInt32(Request.Form["ddlCategories"]);

            if (ModelState.IsValid)
            {
                context.Products.AddObject(products);

                context.SaveChanges();
                products.Photo = FileHelper.UploadPhoto(file, "products", products.ProductId);
                context.SaveChanges();

                UpdateArticles(products);
                UpdateParameterValues(products.CategoryId, products.ProductId);

                return RedirectToAction("List");  
            }
            return View("Create");
        }
        
        //
        // GET: /Catalog/Edit/5
        [HttpGet]
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id)
        {
            Products products = context.Products.Single(x => x.ProductId == id);

            ViewData["Brands"] = new SelectList(context.Brands.ToList(), "BrandId", "Name", products.BrandId);
            ViewData["Categories"] = new SelectList(CategoriesHelper.GetCategories(false, context), "CategoryId", "Name", products.CategoryId);
            ViewData["Parameters"] = ParametersHelper.GetParametersByCategoryId(products.CategoryId);
            ViewData["ParametersValues"] = ParametersValuesHelper.GetParametersValuesForProduct(products.ProductId);

            CurrentArticles = ProductsHelper.GetProductArticles(id, context);

            return View(products);
        }

        //
        // POST: /Catalog/Edit/5
        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(Products products, HttpPostedFileBase file)
        {
            products.BrandId = Convert.ToInt32(Request.Form["ddlBrands"]);
            products.CategoryId = Convert.ToInt32(Request.Form["ddlCategories"]);

            products.Photo = FileHelper.UploadPhoto(file, "products", products.ProductId);

            if (ModelState.IsValid)
            {
                context.Products.Attach(products);
                context.ObjectStateManager.ChangeObjectState(products, EntityState.Modified);

                UpdateParameterValues(products.CategoryId, products.ProductId);
                UpdateArticles(products);

                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View("Edit", products.ProductId);
        }

        public void UpdateParameterValues(int? categoryId, int productId)
        {
            var Category = CategoriesHelper.GetCategoryById(categoryId, context);
            List<Parameters> parameters = ParametersHelper.GetParametersByCategoryId(Category.CategoryId);

            ParametersValuesHelper.DeleteParameters(productId);

            foreach (var param in parameters)
            {
                string value = Request.Form["parameterId-" + param.ParamenterId];
                ParametersValues pv = new ParametersValues()
                {
                    ProductId = productId,
                    ParameterId = param.ParamenterId,
                    Value = value
                };
                context.ParametersValues.AddObject(pv);
            }
            context.SaveChanges();            
        }

        //
        // GET: /Catalog/Delete/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            Products products = context.Products.Single(x => x.ProductId == id);
            return View(products);
        }

        //
        // POST: /Catalog/Delete/5

        [HttpPost, ActionName("Delete")]
        [Authorize(Roles = "Administrators")]
        public ActionResult DeleteConfirmed(int id)
        {
            Products products = context.Products.Single(x => x.ProductId == id);

            ParametersValuesHelper.DeleteParameters(products.ProductId);

            context.Products.DeleteObject(products);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult GetParameters(int categoryId)
        {
            ViewData["Parameters"] = ParametersHelper.GetParametersByCategoryId(categoryId);
            return PartialView("Parameters");
        }

        public ActionResult AddToCart(int id)
        {
            CartHelper.AddProductById(id, context);
            Response.Redirect(Request.UrlReferrer.ToString());
            return null;
        }

        [HttpGet]
        public ActionResult AddArticle()
        {
            return PartialView("AddArticle");
        }

        // POST
        [HttpPost]
        public ActionResult AddArticle(int articleId)
        {
            var article = context.Articles.Where(a => a.ArticleId == articleId).FirstOrDefault();
            CurrentArticles.Add(article);
            return PartialView("ArticlesList", CurrentArticles);
        }

        public ActionResult DeleteArticle(int articleId)
        {
            Articles art = CurrentArticles.Where(p => p.ArticleId == articleId).SingleOrDefault();
            CurrentArticles.Remove(art);

            return PartialView("ArticlesList", CurrentArticles);
        }

        public void UpdateArticles(Products products)
        {
            products.Articles.Clear();
            foreach (Articles art in CurrentArticles)
            {
                products.Articles.Add(new Articles()
                {
                    ArticleId = art.ArticleId,
                    Title = art.Title,
                    Body = art.Body,
                    Photo = art.Photo
                });
            }
            context.SaveChanges();
        }
    }
}